#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：turbo
@File    ：handler.py
@Author  ：赵加响
@Date    ：2024/9/20 11:11 
@Desc    ：
"""
import os.path
from pathlib import Path

from cryptography.fernet import Fernet, InvalidToken


class AESCryptoHandler:
    """
    AES对称加密
    """

    def __init__(self):
        self.current_path = Path(__file__).resolve().parent
        self.secret_key_file = os.path.join(self.current_path, 'aes_secret.key')

    def generate_key(self):
        secret_key = Fernet.generate_key()
        with open(self.secret_key_file, 'wb') as key_file:
            key_file.write(secret_key)

    def read_key(self):
        with open(self.secret_key_file, 'rb') as key_file:
            secret_key = key_file.read()
            return secret_key

    def encrypt(self, data):
        try:
            secret_key = self.read_key()
        except FileNotFoundError:
            return ''
        cipher_suite = Fernet(secret_key)
        encrypted_data = cipher_suite.encrypt(data.encode()).decode()
        return encrypted_data

    def decrypt(self, data):
        if data is None:
            return ''
        try:
            secret_key = self.read_key()
        except FileNotFoundError:
            return ''
        try:
            cipher_suite = Fernet(secret_key)
            decrypted_data = cipher_suite.decrypt(data).decode()
            return decrypted_data
        except InvalidToken:
            return ''


class RSACryptoHandler:
    """
    RSA 非对称加密
    """
    def __init__(self):
        self.public_key = None
        self.private_key = None
